<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 权限,用户身份验证
 * @author 咸洪伟
 */
class Auth
{
	// 用户
	private $_user = array();

	// 是否已经登录
	private $_hasLogin = NULL;

	// 用户组
	public $groups = array();

	//用户组权限
	private $_group_operations=array();

	// CI句柄
	private $_CI;

	// 是否是特殊情况，ajax情况，或者未找到用户组
	private $_is_special = FALSE;

	// 当前模块名,指的是前台还是后台 front,admin
	private $_module;

	// 当前控制器名
	private $_controller;
 	
	// 当前动作名称
	private $_action;
	
	//当前目录
	private $_site_path ;
	
	//存放特殊方式登陆文件的路径
	private $_pathname = './login/';
	
	//文件后缀
	//private $_file_suffix = '.txt';

	/**
	 * 构造函数
	 *
	 * @access public
	 * @return void
	 */
	public function __construct()
	{
		/** 获取CI句柄 */
		$this->_CI = & get_instance();
		
		$this->_site_path = config_item( 'site_path' );
		
		$this->_CI->load->model('admin_model');

		$this->_user = unserialize($this->_CI->session->userdata('user'));
		
		if ($this->_CI->uri->segment(1) === FALSE)
		{
			$this->_module = 0;
		}
		else
		{
			$this->_module = $this->_CI->uri->segment(1);
		}

		if ($this->_CI->uri->segment(2) === FALSE)
		{
			$this->_controller = 0;
		}
		else
		{
			$this->_controller = $this->_CI->uri->segment(2);
		}

		if ($this->_CI->uri->segment(3) === FALSE)
		{
			$this->_action = 'index';
		}
		else
		{
			$this->_action = $this->_CI->uri->segment(3);
		}


	}

	/**
	 * 判断用户是否已经登录
	 *
	 * @access public
	 * @return void
	 */
	public function hasLogin()
	{
		/** 检查session，并与数据库里的数据相匹配 */
		if (NULL !== $this->_hasLogin) {
			return $this->_hasLogin;
		} else {
			if(!empty($this->_user) && NULL !== $this->_user['admin_id']) {
				$user = $this->_CI->admin_model->get_by_pk($this->_user['admin_id']);
				if($user){
					return ($this->_hasLogin = TRUE);
				}
			//文件方式特殊验证是否登录
			} else {
				$ip = str_replace('.', '', $this->_CI->common->get_client_ip());
				$filename = $this->_pathname . md5($ip);
				//文件不存在返回false
				if(!is_file($filename)){
					return ($this->_hasLogin = FALSE);
				}
				//判断文件是否过期
				if(!$this->get_session_time($filename)){
					return ($this->_hasLogin = FALSE);
				}
				//修改文件最后访问时间为当前系统时间
				touch($filename);
				$data = unserialize(trim(file_get_contents($filename)));
				$attributes = array(
						'user_name' => $data['user_name'],
						'password' => $data['password'],
						'last_login_ip' => $data['last_login_ip'],
						'login_method' => 2,
				);
				$total = $this->_CI->admin_model->total($attributes);
				//不存在则返回false
				return $this->_hasLogin = $total ? TRUE : FALSE;
			}
			return ($this->_hasLogin = FALSE);
		}
	}

	public function get_module(){
		$str= $this->_module;
		$str.="_";
		$str.= $this->_controller;
		$str.="_";
		$str.= $this->_action;
		return $str;
	}
	/**
	 * 判断用户权限
	 * @access 	public
	 * @return 	boolean
	 */
	public function check($controller='',$action='')
	{
		//如果不是后台的路径则无需验证
		if ( $this->_module!='admin') return;

		if ( $this->_controller=='site'||$this->_controller=='login') return;

		if ( $this->_is_special ) return;

		$this->_init_grouppermission();
		fb($this->_group_operations);

		if ( $controller && $action ) {
			// 手动检测
			$module_action = "{$controller}_{$action}";
			if ( !isset( $this->_group_operations[$module_action] ) ){
				//fb("无菜单权限".$module_action);
			       	//return FALSE;
			}else{
				//fb("有菜单权限".$module_action);
			}
		} else {

			// 用于开发阶段将所有节点记录
			//$this->_save_module_action();
			//@todo remove
			// 自动检测当前访问的uri
			$module_action = "{$this->_controller}_{$this->_action}";
			fb($module_action);
			//return TRUE;
			if ( !isset( $this->_group_operations[$module_action] ) ){
				fb("无操作权限".$module_action);
				//redirect( base_url( $this->_site_path.'/site/error' ) );
			}else{
				fb("有操作权限".$module_action);
			}
		}

		return TRUE;
	}

	/**
	 * 处理用户登出
	 * @access public
	 * @return void
	 */
	public function process_logout()
	{
		$login_method = $this->get_user('login_method');
		if($login_method==1){
			$this->_CI->session->sess_destroy();
		//特殊方式登陆时删除文件
		}else{
			$ip = str_replace('.', '', $this->_CI->common->get_client_ip());
			$filename = $this->_pathname . md5($ip);
			if(is_file($filename)){
				@unlink($filename);
			}
		}
		redirect($this->_site_path.'/login');
	}

	/**
	 * 处理用户登入
	 * @access public
	 * @param  array $user 用户信息
	 * @return boolean
	 */
	public function process_login($user)
	{
		/** 获取用户信息 */
		$this->_user = $user;
		if($this->_user)
		{
			//特殊登录
			if($user['login_method']==2){
				//当无法获取客户端ip时，禁止登陆
				if($user['login_ip']=='unknown'){
					return FALSE;
				}
				$data = array(
					'user_name' => $user['user_name'],
					'password' => $user['password'],
					'last_login_ip' => $user['login_ip'],
					'group_id' => $user['group_id'],
				);
				if(!file_exists($this->_pathname)){
					@mkdir($this->_pathname);
				}
				//删除特殊登录文件
				$this->delete_login_file($this->_pathname);
				//文件名以ip命名
				$filename = $this->_pathname . md5(str_replace('.', '', $user['login_ip']));
				file_put_contents($filename, serialize($data));
				unset($data);
			}else{
				/** 设置session */
				$this->_set_session();
			}
			return $this->_hasLogin = TRUE;
		}
		return FALSE;
	}

	/**
	 * 设置session
	 *
	 * @access private
	 * @return void
	 */
	private function _set_session()
	{
		$session_data = array('user' => serialize($this->_user));
		
		$this->_CI->session->set_userdata($session_data);
	}

	/**
	 * 获取登录用户的信息
	 */
	public function get_user($field=''){
		
		if(!$field){
			return $this->_user;
		}else{
			if($this->_user[$field]){
				return $this->_user[$field];
			}
			//特殊方式登陆
			$ip = str_replace('.', '', $this->_CI->common->get_client_ip());
			$filename = $this->_pathname . md5($ip);
			if(is_file($filename)){
				$data = unserialize(trim(file_get_contents($filename)));
				return $data[$field] ? $data[$field] : FALSE;
			}
			return FALSE;
		}
	}

	/**
	 * 初始化用户组权限
	 */
	private function _init_grouppermission(){
		fb('here');
		$group_id= $this->_user['group_id'];
		// 权限组ID为空的 一般是没有登陆
		if ( empty( $group_id ) ) {
			$this->_is_special = TRUE;
			return;
		}

		// 如果是ajax 不做权限检查
		if ( $this->_CI->input->is_ajax_request() ) {
			$this->_is_special = TRUE;
			return;
		}

		if(!$this->_group_operations){
			$this->_group_operations=array();

			$this->_CI->load->model('admin_group_operations_model');
			$g_search['attributes']=array('group_id'=>$group_id);
			$grouppermissions=$this->_CI->admin_group_operations_model->all($g_search);

			$ids=array();
			foreach($grouppermissions as $v){
				$ids[]=$v['operations_id'];
			}

			$this->_CI->load->model('operations_model');
			if(!$ids) return;
			$o_search['in']=array('operation_id'=>$ids);
			$permissions= $this->_CI->operations_model->all($o_search);

			foreach($permissions as $v){
				$key=$v['module'].'_'.$v['action'];
				$this->_group_operations[$key]=$v['operation_name'];
			}
		}
	}

	//获取用户组权限
	public function get_group_operations(){
		return $this->_group_operations;
	}
	
	//删除特殊登录文件
	private function delete_login_file($path){
		
		if(!!$source = opendir($path)){
			while (!!$file = readdir($source)){
				if($file=='.' || $file=='..'){
					continue;
				}
				$filename = $path . $file;
				if(is_file($filename)){
					$this->get_session_time($filename);
				}
			}
		}
	}
	
	//获取session有效时间
	private function get_session_time($filename){
		
		//默认1440秒
		$maxlifetime = @ini_get('session.gc_maxlifetime');
		$maxlifetime = $maxlifetime ? $maxlifetime : 1440;
		if(time()-filemtime($filename) > $maxlifetime){
			@unlink($filename);
			return FALSE;
		}
		return TRUE;
	}

}
